<?php

App::uses('AppModel', 'Model');

class LocationReservation extends AppModel {
    
    public $belongsTo = array ('Location', 'Client');
    
    public $validate = array(
        'start' => array(
            array(
                'rule'    => 'notEmpty',
                'message' => 'Morate uneti datum početka rezervacije.'
            ),
            array (
                'rule'    => array('verifyDates'),
                'message' => 'Postoji rezervacija'
            )
        ),
        'end' => array(
            array (
                'rule'    => 'notEmpty',
                'message' => 'Morate uneti datum završetka rezervacije.'
            ),
            array (
                'rule'    => array('verifyDates'),
                'message' => 'Postoji rezervacija'
            )
        )
    );
    
    public function verifyDates() {
        
        $reservationId = (int)@$this->data[$this->name]['id'];
        $start      = $this->data[$this->name]['start'];
        $end        = $this->data[$this->name]['end'];
        $locationId = $this->data[$this->name]['location_id'];
        
        $conditions = array(
            "{$this->name}.location_id ="   => $locationId,
            'OR' => array(
                "{$this->name}.start BETWEEN '{$start}' AND '{$end}'",
                "{$this->name}.end   BETWEEN '{$start}' AND '{$end}'",
                "{$this->name}.start < '{$start}' AND {$this->name}.end > '{$end}'"
            )
        );
        if ($reservationId) {
            $conditions["{$this->name}.id !="] = $reservationId;
        }
        
        
        $count = $this->find('count', array('conditions' => $conditions));
        return $count>0 ? false : true;
    }
}
